/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    //注意一定要传入引用，否则pos在其他地方++了，但是出了函数栈后又没变
    TreeNode* _buildTree(vector<int>& preorder, vector<int>& inorder, int& pos, int left, int right)
    {
        if (left > right || pos >= preorder.size())
            return nullptr;
        
        int index = 0;
        for (; inorder[index] != preorder[pos]; index++);

        TreeNode* root = new TreeNode(preorder[pos++]);
        root->left = _buildTree(preorder, inorder, pos , left, index - 1);
        root->right = _buildTree(preorder, inorder, pos, index + 1, right);

        return root;
    }
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int pos = 0;
        return _buildTree(preorder, inorder, pos, 0, inorder.size());
    }
};